<?php
require_once PATH_SITE.'cn/royan/php/utils/Crypt.class.php';
require_once PATH_SITE.'cn/royan/php/parses/ConnectParse.parse.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once PATH_SITE.'org/puremvc/php/patterns/proxy/Proxy.php';
/**
 * Description of DataPackageProxy
 *
 * @author yanr
 */
class ReceiveDataProxy extends Proxy
{
    const NAME = "DataPackageProxy";
    
    protected $crypt;
    protected $socketProxy;

    //put your code here
    public function __construct() {
        parent::__construct( ReceiveDataProxy::NAME );
        
        $this->crypt = Crypt::getInstance();
        
        $this->socketProxy = $this->facade->retrieveProxy( SocketProxy::NAME );
    }
    
    public function parse( $data )
    {
        IF( $data["message"] === "<policy-file-request/>\0" ){
            $this->sendNotification( ApplicationMediator::SAY_HELLO_TO_CLIENT, $data["client"] );
        }
        ELSE{
            $this->receiveMessageHandler( $data["message"], $data["client"] );
        }
    }
    
    private function receiveMessageHandler( $message, $client, $cryptable = TRUE )
    {
        if( $cryptable ){
            //echo $this->byteArrayToString( $message, 'utf-8' );
            //$message = $this->crypt->decrypt( $message );
        }
        Logger::trace( "receive message:\r\n".$message."\r\nfrom ".$client );
        
        $info = json_decode($message);
        $socket = /*&*/ $this->socketProxy->getData();
        $clients = & $socket->__get( "clientInfos" );
        
        FOR( $i = 0; $i < count( $clients ); $i++ )
        {
            IF( isset( $clients[$i] ) && $clients[$i]->__get("socket") == $client )
            {
                $user = $clients[$i];
                $data = array( "type"=>$info->type,
                               "data"=>$info,
                               "user"=>$user );
                
                $connectProxy = ConnectParse::getInstance();
                $connectProxy->parseInfo( $data );
                BREAK;
            }
        }    
    }
    
    private function stringToByteArray( $str, $charset )
    {  
        $str = iconv($charset,'UTF-16',$str);
        preg_match_all('/(.)/s',$str,$bytes);
        $bytes = array_map('ord',$bytes[1]);
        return $bytes;
    }  

    private function byteArrayToString( $bytes, $charset )
    {  
        $bytes = array_map('chr',$bytes);
        $str = implode('',$bytes);
        $str = iconv('UTF-16',$charset,$str);
        return $str;
    }
}

?>
